import React, {useState, useEffect} from 'react'
import {Button} from 'antd'
import CustomTable from '@/components/Table'
import {
	getErrBaseExcelList,
	getTaskInventory,
	requisitionImport,
} from '@/service/storage/inventoryTask'
import {downloadDocumentUrl} from '@/service/common/download'
import BatchUpload from '@/components/BatchUpload'
import {modalApi} from '@/utils/modalReq'

function Inventlist(props: {
	taskId: any
	status: boolean
	page: any
	setPage: React.Dispatch<
		React.SetStateAction<{
			current: number
			size: number
		}>
	>
}) {
	const {taskId, status, page, setPage} = props

	const [total, setTotal] = useState(0)
	const [tableList, setTableList] = useState([]) // 处理动态列表的数据源
	const [columns, setColumns] = useState([]) // 处理动态列表的数据源
	const [isUploadModalOpen, setIsUploadModalOpen] = useState(false)

	const getDynamic = () => {
		const params = {
			...page,
			taskId,
		}
		getTaskInventory(params).then((res) => {
			// 处理动态列表
			const columnsDynamic = res?.data?.header.map(
				(item: any, index: any) => ({
					key: index,
					title: `${item}`,
					dataIndex: `col${index}`,
					width: 180,
					align: 'center',
					ellipsis: true,
				}),
			)
			setColumns(columnsDynamic)
			setTotal(res?.data?.total)
			const tableDynamic = res?.data?.contents.map((ele: any) =>
				ele.reduce(
					(pre: any, cut: any, _index: any) =>
						Object.assign(pre, {[`col${_index}`]: cut}),
					{},
				),
			)
			setTableList(tableDynamic)
		})
	}

	const errorColumns = [
		{
			title: '车辆ID',
			dataIndex: '车辆ID',
			align: 'center',
		},
		{
			title: '错误消息',
			dataIndex: 'errorMsg',
			align: 'center',
		},
	]

	useEffect(() => {
		getDynamic()
	}, [taskId, page])
	return (
		<div>
			<div style={{marginBottom: 10}}>
				<Button
					disabled={status}
					onClick={() => {
						downloadDocumentUrl({
							resourceId: '194',
							queryDesc: '下载盘点任务表,resourceId:194',
							queryParam: {
								taskId,
							},
						})
					}}>
					下载盘点表
				</Button>
				<Button
					disabled={status}
					style={{margin: '0 8px'}}
					onClick={() => setIsUploadModalOpen(true)}>
					导入盘点结论
				</Button>
			</div>
			<CustomTable
				kid="carPlateNo"
				params={page}
				columns={columns}
				pagination
				total={total}
				callback={(pagination: any) => {
					setPage(pagination)
				}}
				loading={false}
				dataSource={tableList}
			/>
			<BatchUpload
				isModalOpen={isUploadModalOpen}
				setIsModalOpen={setIsUploadModalOpen}
				importData={requisitionImport}
				onTableList={getErrBaseExcelList}
				getListData={getDynamic}
				fileNmae="file"
				typeUp={false}
				takeId={taskId}
				uploadFileUrl={`${modalApi.carMessage}/stocktake-data-list/task/import/check`}
				columns={errorColumns}
			/>
		</div>
	)
}

export default Inventlist
